import { computed, onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { useListPage } from "@/composables/useListPage";
import permissionsApi, {
  type PermissionItem,
  type PermissionPayload,
  type PermissionListParams,
  type PermissionListResult
} from "@/api/access/permissions";

interface PermissionFilterForm {
  keyword: string;
  client_type: string;
  status: string | number;
}

interface PermissionFormModel {
  id: number;
  name: string;
  code: string;
  type: string;
  client_type: string;
  status: number;
  description: string;
}

const DEFAULT_FILTER: PermissionFilterForm = {
  keyword: "",
  client_type: "",
  status: ""
};

const DEFAULT_FORM: PermissionFormModel = {
  id: 0,
  name: "",
  code: "",
  type: "action",
  client_type: "admin",
  status: 1,
  description: ""
};

const CLIENT_TYPES = [
  { label: "后台管理", value: "admin" },
  { label: "卖家端", value: "seller" },
  { label: "买家端", value: "buyer" },
  { label: "桌面端", value: "desktop" },
  { label: "移动端", value: "mobile" }
];

const STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "已启用", value: 1 },
  { label: "已禁用", value: 0 }
];

const PERMISSION_TYPES = [
  { label: "页面/菜单", value: "menu" },
  { label: "接口操作", value: "action" },
  { label: "数据范围", value: "data" }
];

const columns: TableColumnList = [
  { label: "权限ID", prop: "id", width: 90 },
  { label: "权限名称", prop: "name", minWidth: 200, align: "left" },
  { label: "权限标识", prop: "code", minWidth: 220, align: "left" },
  { label: "权限类型", prop: "type", width: 120, slot: "type" },
  { label: "所属端", prop: "client_type", width: 120, slot: "clientType" },
  { label: "状态", prop: "status", width: 110, slot: "status" },
  { label: "更新时间", prop: "updated_at", minWidth: 180 },
  {
    label: "操作",
    prop: "operation",
    width: 200,
    fixed: "right",
    slot: "operation"
  }
];

export function usePermissionPage() {
  const permissionDialogVisible = ref(false);
  const permissionDialogTitle = ref("新增权限");
  const permissionFormRef = ref<FormInstance>();
  const permissionForm = reactive<PermissionFormModel>({ ...DEFAULT_FORM });
  const saving = ref(false);

  const {
    formState: filterForm,
    pagination,
    dataList,
    loading,
    onSearch,
    resetForm: resetFilter,
    handlePageChange,
    handleSizeChange
  } = useListPage<PermissionFilterForm, PermissionItem, PermissionListResult>(
    {
      fetch: params =>
        permissionsApi.fetchList({
          ...params,
          keyword: params.keyword,
          client_type: params.client_type,
          status: params.status
        } as PermissionListParams)
    },
    DEFAULT_FILTER,
    {},
    {
      responseAdapter: response => ({
        list: response.list,
        total: response.total,
        pageSize: response.pageSize,
        currentPage: response.currentPage
      })
    }
  );

  const tableData = computed(() => dataList.value ?? []);

  const rules: FormRules<PermissionFormModel> = {
    name: [
      { required: true, message: "请输入权限名称", trigger: "blur" },
      { min: 2, max: 80, message: "长度需在 2-80 个字符内", trigger: "blur" }
    ],
    code: [
      { required: true, message: "请输入权限标识", trigger: "blur" },
      {
        pattern: /^[a-z][a-z0-9:._-]{2,99}$/,
        message: "标识需以字母开头，可包含数字、:._-",
        trigger: "blur"
      }
    ],
    client_type: [
      { required: true, message: "请选择端类型", trigger: "change" }
    ],
    type: [{ required: true, message: "请选择权限类型", trigger: "change" }],
    status: [{ required: true, message: "请选择状态", trigger: "change" }],
    description: [{ max: 200, message: "描述不超过 200 字", trigger: "blur" }]
  };

  const handleSearch = async () => {
    filterForm.page = 1;
    await onSearch();
  };

  const handleResetFilters = async () => {
    await resetFilter();
  };

  const resetDialogForm = () => {
    Object.assign(permissionForm, { ...DEFAULT_FORM });
  };

  const openCreate = () => {
    permissionDialogTitle.value = "新增权限";
    resetDialogForm();
    permissionDialogVisible.value = true;
  };

  const openEdit = (row: PermissionItem) => {
    permissionDialogTitle.value = "编辑权限";
    resetDialogForm();
    permissionForm.id = row.id;
    permissionForm.name = row.name;
    permissionForm.code = row.code;
    permissionForm.type = row.type ?? "action";
    permissionForm.client_type = row.client_type ?? "admin";
    permissionForm.status = Number(row.status ?? 1) as 0 | 1 | number;
    permissionForm.description = row.description ?? "";
    permissionDialogVisible.value = true;
  };

  const submitPermission = async () => {
    const formRef = permissionFormRef.value;
    if (!formRef) return;
    try {
      await formRef.validate();
    } catch {
      return;
    }

    const payload: PermissionPayload = {
      name: permissionForm.name,
      code: permissionForm.code,
      type: permissionForm.type,
      client_type: permissionForm.client_type,
      status: permissionForm.status,
      description: permissionForm.description || null
    };

    saving.value = true;
    try {
      if (permissionForm.id === 0) {
        await permissionsApi.create(payload);
        message("权限创建成功", { type: "success" });
      } else {
        await permissionsApi.update(permissionForm.id, payload);
        message("权限信息已更新", { type: "success" });
      }
      permissionDialogVisible.value = false;
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "保存权限失败", { type: "error" });
    } finally {
      saving.value = false;
    }
  };

  const handleDelete = async (row: PermissionItem) => {
    try {
      await ElMessageBox.confirm(
        `确认删除权限「${row.name}」吗？`,
        "删除确认",
        {
          type: "warning",
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await permissionsApi.remove(row.id);
      message("权限已删除", { type: "success" });
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "删除权限失败", { type: "error" });
    }
  };

  onMounted(async () => {
    await onSearch();
  });

  return {
    filterForm,
    pagination,
    tableData,
    columns,
    loading,
    handleSearch,
    handleResetFilters,
    handlePageChange,
    handleSizeChange,

    permissionDialogVisible,
    permissionDialogTitle,
    permissionForm,
    permissionFormRef,
    rules,
    saving,
    openCreate,
    openEdit,
    submitPermission,
    handleDelete,

    clientTypes: CLIENT_TYPES,
    statusOptions: STATUS_OPTIONS,
    permissionTypes: PERMISSION_TYPES
  };
}
